/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-10-09 09:55:48
 * @LastEditors: cxguo
 * @LastEditTime: 2020-09-09 16:30:13
 */
import { asyncRoutes, constantRoutes, clonedeepRouters } from '@/router'
import store from '@/store'

/**
 * Filter asynchronous routing tables by recursion
 * 统计sonmenu 有权限的个数
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  const _routes = clonedeepRouters(routes)
  const res = []
  const appData = store.getters.appData
  const hasPermissions = appData.permissions
  const perRouters = _routes.filter(item => { return ['/', '*'].indexOf(item.path) === -1 })
  const constRouters = _routes.filter(item => { return ['/', '*'].indexOf(item.path) !== -1 })
  res.push(...constRouters)
  perRouters.forEach(item => {
    const children = item.children
    let sonHasPerCount = 0
    const childrenRes = []
    children.forEach((c, index) => {
      const perm = c.meta.perm
      // console.log('perm:', perm, hasPermissions)
      if (hasPermissions.indexOf(perm) !== -1) {
        // 拥有权限
        // console.log('有权限：', perm)
        childrenRes.push(c)
        sonHasPerCount++
      }
      if (!perm) {
        childrenRes.push(c)
      }
    })
    // console.log('sonHasPerCount', sonHasPerCount)
    if (sonHasPerCount > 0) {
      // son里面有一个有权限的就push进去
      item.children = childrenRes
      res.push(item)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
